package io.mycat.eye.web.controller;

import java.sql.Timestamp;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.mycat.eye.web.bean.MycatBackend;
import io.mycat.eye.web.bean.MycatConnection;
import io.mycat.eye.web.dto.ChatDataDto;
import io.mycat.eye.web.dto.RestResponse;
import io.mycat.eye.web.service.MycatBackendService;
import io.mycat.eye.web.service.MycatConnectionService;
import io.mycat.eye.web.service.MycatStatusService;

/**
 * Created by xqy on 18/5/3.
 */
@RestController
@RequestMapping("/mycat/status")
public class MycatStatusController {
    Logger logger = LoggerFactory.getLogger(MycatStatusController.class);
    
    public static final String SUCCESSFUL = "successful";

    @Autowired
    MycatStatusService mycatStatusService;

    @Autowired
    MycatConnectionService mycatConnectionService;

    @Autowired
    MycatBackendService mycatBackendService;

    @GetMapping(value = "all")
    public ResponseEntity<RestResponse<Object>> getServerStatus(@RequestParam("server_id") Integer serverId, String timeRange){
        logger.debug("status === serverId:{} time_range:{}", serverId, timeRange);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, SUCCESSFUL);
        if(serverId == 0){
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if(timeRange==null){
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if(times.length<=1){
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try {
            ChatDataDto dto = mycatStatusService.getServerStatus(serverId, beginTime, endTime);
            response.setData(dto);
            return new ResponseEntity<>(response,HttpStatus.OK);
        }catch (Exception e){
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response,HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "connection")
    public ResponseEntity<RestResponse<Object>> getMycatConnection(@RequestParam("server_id") Integer serverId, String timeRange){
        logger.debug("connection === serverId:{} time_range:{}", serverId, timeRange);
        RestResponse<Object> response = RestResponse.buildExceptionResponse(200, SUCCESSFUL);
        if(serverId == 0){
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
        }
        if(timeRange==null){
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
        }
        String[] times = timeRange.split("-");
        if(times.length<=1){
            response.setCode(401);
            response.setMessage("参数错误");
            return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
        }
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try{
            List<MycatConnection> list = mycatConnectionService.getConnection(serverId, Timestamp.valueOf(beginTime).getTime(),Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response,HttpStatus.OK);
        }catch (Exception e){
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @GetMapping(value = "backend")
    public ResponseEntity<Object> getMycatBackend(@RequestParam("server_id") Integer serverId, String timeRange){
    	RestResponse<Object> response = RestResponse.buildExceptionResponse(200, SUCCESSFUL);
    	if(checkParam(serverId, timeRange, response) != null) {
    		new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
    	}
    	String[] times = timeRange.split("-");
        String beginTime = times[0].trim().replace("/", "-");
        String endTime = times[1].trim().replace("/", "-");
        try{
            List<MycatBackend> list = mycatBackendService.getBackend(serverId,Timestamp.valueOf(beginTime).getTime(),Timestamp.valueOf(endTime).getTime());
            response.setData(list);
            return new ResponseEntity<>(response,HttpStatus.OK);
        }catch (Exception e){
            response.setCode(500);
            response.setMessage(e.getMessage());
            return new ResponseEntity<>(response,HttpStatus.SERVICE_UNAVAILABLE);
        }
    }
    
    public RestResponse<Object> checkParam(@RequestParam("server_id") Integer serverId, String timeRange, RestResponse<Object> response) {
    	logger.debug("backend === serverId:{} time_range:{}", serverId, timeRange);
        if(serverId == 0){
            response.setCode(401);
            response.setMessage("节点ID不可为空");
            return response;
        }
        if(timeRange==null){
            response.setCode(401);
            response.setMessage("日期范围不可为空");
            return response;
        }
        String[] times = timeRange.split("-");
        if(times.length<=1){
            response.setCode(401);
            response.setMessage("参数错误");
            return response;
        }
        return null;
    }
}
